
# launch_server_with_rt_cov.py
# Run the user's Modbus TCP server under real-time coverage snapshots.
import sys, os, importlib.util, inspect
from pathlib import Path
from realtime_coverage import RealTimeCoverage

# Config (edit if needed)
SERVER_PATH = os.environ.get("SERVER_PATH", "./modbus_full_stack_schemeB.py")
HOST = os.environ.get("SERVER_HOST", "0.0.0.0")
PORT = int(os.environ.get("SERVER_PORT", "1502"))
SNAPSHOT_SEC = float(os.environ.get("COV_INTERVAL_SEC", "30"))
CSV_OUT = os.environ.get("COV_CSV", "./server_cov_timeseries.csv")

def load_module_from_path(path, module_name="user_server_mod"):
    spec = importlib.util.spec_from_file_location(module_name, path)
    mod = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = mod
    spec.loader.exec_module(mod)  # type: ignore
    return mod

def main():
    rt = RealTimeCoverage(interval_sec=SNAPSHOT_SEC, out_csv=CSV_OUT, branch=True, concurrency=("thread",))
    rt.start()
    try:
        mod = load_module_from_path(SERVER_PATH, "user_server_mod")
        # Try to find a 'main' and call it with CLI-like args if supported.
        entry = getattr(mod, "main", None)
        if entry is None:
            # Fallback: execute as script (rarely needed since we already imported above)
            import runpy
            # Make argv for the script if it parses CLI
            sys.argv = [SERVER_PATH, "--host", HOST, "--port", str(PORT)]
            runpy.run_path(SERVER_PATH, run_name="__main__")
        else:
            sig = inspect.signature(entry)
            if len(sig.parameters) == 0:
                # The user's server main() might use argparse inside with sys.argv — set argv
                sys.argv = [SERVER_PATH, "--host", HOST, "--port", str(PORT)]
                entry()
            else:
                # main(argv) style
                entry(["--host", HOST, "--port", str(PORT)])
    finally:
        rt.stop()

if __name__ == "__main__":
    main()
